package com.regulaforensics.date_reminder;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;

public class ReminderService extends Service {
	
	Alarm alarm = new Alarm();
	private static final String TAG = "ServiceRemder";
	public static final String BROADCAST_ACTION = "com.regulaforensics.date_reminder.DISPLAYUPDATE";
	public static final String RERUN = "RERUN";
	public static int NOTIFICATION_ID = 1;
    Intent intent;
	
  
   @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
    	SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
    	SharedPreferences.Editor editor = settings.edit();
    	editor.putInt(DateReminderActivity.SERVICE_RUNNING, 1);
	        // Commit the edits!
	    editor.commit();
	        
//    	Toast.makeText(ReminderService.this, "Service Create", Toast.LENGTH_LONG).show();
    	intent = new Intent(BROADCAST_ACTION);
    	setAlarm();
    }
    
    private void setAlarm(){
    	boolean alarmRunning = alarm.isAlarmRunning();
    	if(alarmRunning==false){
    		alarm.SetAlarm(this.getApplicationContext());
    	}
    }
    
    private void cancelAlarm(){
    	
    	alarm.CancelAlarm(this.getApplicationContext());
    }
    
    public void resetAlarm(){
    	alarm.CancelAlarm(this.getApplicationContext());
    	alarm.SetAlarm(this.getApplicationContext());
    }
    
    

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		int rerun=0;
		try{
			///get info from intent if int ==1 then this started from Preference activity
			Bundle extras = intent.getExtras();
			if (extras != null) {
	        	rerun = extras.getInt(RERUN);
	        }
			if(rerun==1){
				resetAlarm();
				return;
			}
				
			
			SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
			
			ReminderDbAdapter dbHelper= MyAppDateReminder.getDatabaseAdapter();
			
			Log.d(TAG, "OnStart Service");
			
			
			Cursor cont_cur=getContacts();
			cont_cur.moveToFirst();
			Cursor reminder = dbHelper.fetchContacts();
			boolean find=false;
			boolean need_update=false;
			
			Log.d(TAG, "cont_count=" + cont_cur.getCount() + " reminder count = "+ reminder.getCount());
			
			if (cont_cur.getCount() > 0) {
	    	    do {
	    	        int id = cont_cur.getInt(cont_cur.getColumnIndex(ContactsContract.Contacts._ID));
	    	        
	    	        if(reminder.getCount()!=0){
	    	        	reminder.moveToFirst();//back to first
	    	        	do {
	    	        		int cont_id_rem = reminder.getInt(reminder.getColumnIndex(ReminderDbAdapter.KEY_CONT_ID));
	    	        		if(cont_id_rem==id){
	    	        			//from bd
	        	        		int id_rem = reminder.getInt(reminder.getColumnIndex(ReminderDbAdapter.KEY_ROWID));
	        	        		String name_rem = reminder.getString(reminder.getColumnIndex(ReminderDbAdapter.KEY_SUMMARY));
	        	        		int day_rem = reminder.getInt(reminder.getColumnIndex(ReminderDbAdapter.KEY_DAY));
	        	        		int month_rem = reminder.getInt(reminder.getColumnIndex(ReminderDbAdapter.KEY_MONTH));
	        	        		int year_rem = reminder.getInt(reminder.getColumnIndex(ReminderDbAdapter.KEY_YEAR));
	        	        		int cont_del_rem = reminder.getInt(reminder.getColumnIndex(ReminderDbAdapter.KEY_CONT_DEL));
	        	        		
	        	        		//from contacts
	        	        		String birthday = cont_cur.getString(cont_cur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
		    	        		SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd"); 
			    	        	Date myDate = curFormater.parse(birthday);
			    	        	int contYear = myDate.getYear()+1900;
			    	        	int contMonth = myDate.getMonth();
			    	        	int contDay = myDate.getDate();
		    	        		String name = cont_cur.getString(cont_cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
	        	        		
		    	        		if((contYear!=year_rem) || (contMonth!=month_rem) || (contDay!=day_rem) || (!name.equals(name_rem))){
		    	        			dbHelper.updateTodo((long)id_rem, name, null, contYear, contMonth, contDay, 1, id, cont_del_rem);
		    	        			Log.d(TAG, "Update data in reminder=" + name);
		    	        			need_update = true;
		    	        		}
		    	        		Log.d(TAG, "Find cont in reminder=" + name);
	        	        		find = true;
	        	        		break;
	    	        		}
						} while (reminder.moveToNext());
	    	        	//add new reminder
	    	        	if(find==false){
	    	        		String birthday = cont_cur.getString(cont_cur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
	    	        		SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd"); 
		    	        	Date myDate = curFormater.parse(birthday);
		    	        	int contYear = myDate.getYear()+1900;
		    	        	int contMonth = myDate.getMonth();
		    	        	int contDay = myDate.getDate();
	    	        		String name = cont_cur.getString(cont_cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
	    	        		dbHelper.createTodo(name, null, contYear, contMonth, contDay, 1, id, 0);
	    	        		Log.d(TAG, "Add new cont, not found in reminder = " + name);
	    	        		need_update = true;
	    	        	}
	    	        	
	    	        }  
	    	        else{
	    	        	///add new reminder
	    	        	String birthday = cont_cur.getString(cont_cur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
	    	        	SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd"); 
	    	        	Date myDate = curFormater.parse(birthday);
	    	        	int contYear = myDate.getYear()+1900;
	    	        	int contMonth = myDate.getMonth();
	    	        	int contDay = myDate.getDate();
		        		String name = cont_cur.getString(cont_cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
		        		dbHelper.createTodo(name, "Contact Birthday", contYear, contMonth, contDay, 1, id, 0);
		        		Log.d(TAG, "nothing in reminder, add new cont = " + name);
		        		need_update = true;
	    	        }
	    	        find=false;
	                } while (cont_cur.moveToNext());
	        }
			
			
			reminder.moveToFirst();//back to first
			cont_cur.moveToFirst();
			
			int rem_count = reminder.getCount();
			int cont_count = cont_cur.getCount();
			
			if((rem_count>cont_count && rem_count>0)){///Necessary to deletecontacts from reminder
				
				if(cont_count == 0){ ///delete all from reminder
					do {
						int rem_id = reminder.getInt(reminder.getColumnIndex(ReminderDbAdapter.KEY_ROWID));
						dbHelper.deleteTodo(rem_id);
					} while (reminder.moveToNext());
				}
				else{
					
					do {
						int cont_id_rem = reminder.getInt(reminder.getColumnIndex(ReminderDbAdapter.KEY_CONT_ID));
						int id_rem = reminder.getInt(reminder.getColumnIndex(ReminderDbAdapter.KEY_ROWID));
						find=false;
						
						cont_cur.moveToFirst();
						do {
							int id = cont_cur.getInt(cont_cur.getColumnIndex(ContactsContract.Contacts._ID));
							if(cont_id_rem==id){
	    	        			
		    	        		Log.d(TAG, "Find cont in contacts=" + id);
	        	        		find = true;
	        	        		break;
							}
						} while (cont_cur.moveToNext());
						
						if(find==false){//delete
							dbHelper.deleteTodo(id_rem);
						}
					} while (reminder.moveToNext());
			}
			}
	        
			cont_cur.close();
	        reminder.close();
	        
	        
	        ///sync with calendar
	        
	        
	        //update UI
	        if(need_update == true){
	        	Context context = getApplicationContext();
	        	Intent myintent = new Intent();
	        	myintent.setAction(BROADCAST_ACTION);
				context.sendBroadcast(myintent);
	        }
	        
	        
	        final Calendar current = Calendar.getInstance(); 
		    int currDay = current.get(Calendar.DAY_OF_MONTH);
		    int currMonth = current.get(Calendar.MONTH);
	        Cursor today = dbHelper.fetchTodayReminder(currMonth, currDay);
	        
	        int today_count = today.getCount();
	        
	        int AlarmOnOff =  settings.getInt(DateReminderActivity.ALARMONOFF, 1);
	        
	        if(today_count>0 && AlarmOnOff==1)
	        {
	        	 ////find birthday to notify!
	        	int rem = today_count % 10;
	        	
	        	NotificationManager notificationManager =(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	        	int icon = R.drawable.notification;        // icon from resources
	        	CharSequence tickerText = getString(R.string.notificationTickerStart)+" "+ today_count +" ";  // ticker-text
	        	if(today_count==1 || (rem==1 && today_count>11))
	        		tickerText = tickerText + getString(R.string.notificationTickerEnd1);
	        	else
	        		tickerText = tickerText + getString(R.string.notificationTickerEnd);
	        	
	        	long when = System.currentTimeMillis();         // notification time
	        	Context context = getApplicationContext();      // application Context
	        	CharSequence contentTitle = getString(R.string.notificationContentTitle);  // message title
	        	CharSequence contentText = getString(R.string.notificationContentStart) + " "+ today_count +" ";      // message text
	        	if(today_count==1 || (rem==1 && today_count>11))
	        		contentText = contentText + getString(R.string.notificationContentEnd1);
	        	else
	        		contentText = contentText + getString(R.string.notificationContentEnd);

	        	Intent notificationIntent = new Intent(context, DateReminderActivity.class);
	        	notificationIntent.putExtra(DateReminderActivity.START_FROM_NOTIFICATION, 1);
	        	PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

	        	// the next two lines initialize the Notification, using the configurations above
	        	Notification notification = new Notification(icon, tickerText, when);
	        	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
	        	
	        	notification.defaults|= Notification.FLAG_AUTO_CANCEL;
	        	notification.flags |= Notification.FLAG_AUTO_CANCEL;
	        	
	        	
				int checkVibra =  settings.getInt(DateReminderActivity.VIBRATE, 0);
	        	
				if(checkVibra==1){
					notification.defaults |= Notification.DEFAULT_VIBRATE;
					long[] vibrate = {0,100,200,300};
					notification.vibrate = vibrate;
				}
	
	        	notificationManager.notify(NOTIFICATION_ID, notification);
	        }
	        
	        today.close();
	        
	        	
		}
		catch(Exception ex){
			Context context = getApplicationContext();  
		    CharSequence text = ex.toString();  
		    int duration = Toast.LENGTH_LONG;  
		    Toast toast = Toast.makeText(context, "ReminderService " + text, duration);  
		    toast.show();  
		}	    
	    
		
	}
	
	private Cursor getContacts() {
        // Run query
        Uri uri = ContactsContract.Data.CONTENT_URI;
        ContentResolver cr = this.getBaseContext().getContentResolver();

        String[] projection = new String[] {
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID,
                ContactsContract.CommonDataKinds.Event.CONTACT_ID,
                ContactsContract.CommonDataKinds.Event.START_DATE
        };

        String where =
                ContactsContract.Data.MIMETYPE + "= ? AND " +
                ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
        String[] selectionArgs = new String[] {ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE};
        String sortOrder = null;
        return 	cr.query(uri, projection, where, selectionArgs, sortOrder);
    }

	private Cursor getCalendarEvents() {
		
		String[] projection = new String[]{"title", "dtstart", "dtend", "rrule", "rdate", "_id"};
		 Uri calendars;
		    if (Build.VERSION.SDK_INT >= 8 ) {
		    	calendars = Uri.parse("content://com.android.calendar/events");
		    } else {
		    	calendars = Uri.parse("content://calendar/calendars");
		    }
		    
		Context context = getApplicationContext();      // application Context
		     
		return context.getContentResolver().query(calendars, projection,"rrule LIKE '%YEARLY%'", null, null);
		
	}
	
	@Override
    public void onDestroy() {
        super.onDestroy();
        
    	SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
    	SharedPreferences.Editor editor = settings.edit();
    	editor.putInt(DateReminderActivity.SERVICE_RUNNING, 0);
	        // Commit the edits!
	    editor.commit();
	    
        cancelAlarm();      
//        Toast.makeText(ReminderService.this, "Service Stop", Toast.LENGTH_LONG).show();
    }
}